package com.heima.datasync.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.heima.datasync.mapper.ApArticleMapper;
import com.heima.datasync.service.EsDataService;
import com.heima.model.article.pojo.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vo.SearchArticleVo;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * Created by ZYJ on 2021/6/8 17:32
 * 初始化把mysql 的文章存到es
 */
@Service
public class EsDataServiceImpl implements EsDataService {
    @Autowired
    ApArticleMapper apArticleMapper;
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    public static final String ARTICLE_INDEX_NAME = "app_info_article";

    @Override
    public ResponseResult dataInit() {
        List<ApArticle> allArticles = apArticleMapper.findAllArticles();
        //校验
        if(allArticles == null || allArticles.size() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "数据库文章信息不存在");
        }
        BulkRequest bulkRequest = new BulkRequest(ARTICLE_INDEX_NAME);
        for (ApArticle aprticle : allArticles) {
            //封装数据
            SearchArticleVo articleVo = new SearchArticleVo();
            BeanUtil.copyProperties(aprticle,articleVo);
            //把vo转成json
            String articleVoJson = JSON.toJSONString(articleVo);
            //创建添加文档对象 IndexRequest设置id request.id
            //   设置数据 source(json,指定json类型)
            IndexRequest indexRequest = new IndexRequest()
                    .id(aprticle.getId().toString())
                    .source(articleVoJson, XContentType.JSON);
            //添加到批量导入的对象中
            bulkRequest.add(indexRequest);
        }
        //client.bulk 执行
        try {
            BulkResponse reponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            return ResponseResult.okResult(reponse.status());
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, e.getMessage());
        }

    }
}
